package cn.com.thinker.security.sdk.sso.key.impl;

import cn.com.thinker.core.tools.spring.SpringContextUtils;
import cn.com.thinker.security.sdk.shiro.propertise.ShiroProperties;
import cn.com.thinker.security.sdk.sso.key.KeyService;
import cn.com.thinker.security.sdk.sso.key.Thin4soKey;
import cn.com.thinker.security.sdk.tools.SsoUtils;
import cn.com.thinker.tools.web.http.Http;
import cn.com.thinker.tools.web.http.Https;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.velocity.app.event.implement.EscapeXmlReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 默认的秘钥信息获取实现类，该类只是一个简单的实现，非常不安全。 在生产环境，建议请使用公钥和私钥的方式对秘钥信息
 * 进行加密，避免秘钥在公网环境下泄露。请自行加强安全性。
 *
 * @author crazyhc
 */
@SuppressWarnings("deprecation")
public class DefaultKeyServiceImpl implements KeyService {

    private static Logger logger = Logger.getLogger(DefaultKeyServiceImpl.class
            .getName());

    private String thin4soServerFetchKeyUrl;

    /**
     * 本应用的秘钥信息。
     */
    private Thin4soKey thin4soKey;

    /**
     * 本应用的应用id.
     */
    private String appId;


    public DefaultKeyServiceImpl(String thin4soServerFetchKeyUrl, String appId) {
        super();
        this.thin4soServerFetchKeyUrl = thin4soServerFetchKeyUrl;
        this.appId = appId;
    }

    @Override
    public Thin4soKey findKeyByAppId(String appId) {
        if (thin4soKey == null) {
            // do fetch key from remote server.
            this.thin4soKey = fetchKeyFromThin4soServer();
        }
        return thin4soKey;
    }

    /**
     * TODO 以后改为本地保存
     *
     * @return
     */
    private Thin4soKey fetchKeyFromThin4soServer() {

        Map<String, String> map = Maps.newHashMap();
        map.put("appId", this.appId);

        thin4soServerFetchKeyUrl = SsoUtils.chooseUrl(thin4soServerFetchKeyUrl);

        Http post = Http.post(thin4soServerFetchKeyUrl).ssl().params(map);
        try {
            return post.request(Thin4soKey.class);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "fetch thin4so key from server error, the url is [" + thin4soServerFetchKeyUrl + "]", e);
        }

        return null;
    }

    @Override
    public Thin4soKey findKeyByKeyId(String keyId) {
        if (thin4soKey == null) {
            return this.findKeyByAppId(null);
        }
        return thin4soKey;
    }

}
